package com.haidechizi.sort;

import java.util.Arrays;

public class RadixSort {

    public static void main(String[] args) {
        int[] arr = new int[]{9, 11, 13, 56, 3, 4, 8, 15, 18, 65};
        radixSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void radixSort(int[] arr) {
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (max < arr[i]) {
                max = arr[i];
            }
        }

        int maxLength = String.valueOf(max).length();

        int[][] temp = new int[10][arr.length];
        int[] counts = new int[10];
        for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
            for (int j = 0; j < arr.length; j++) {
                int ys = arr[j] / n % 10;
                temp[ys][counts[ys]] = arr[j];
                counts[ys]++;
            }
            //
            int index = 0;
            for (int k = 0; k < counts.length; k++) {
                if (counts[k] > 0) {
                    for (int l = 0; l < counts[k]; l++) {
                        arr[index] = temp[k][l];
                        index++;
                    }
                    counts[k] = 0;
                }
            }
        }
    }
}
